package com.wang.jmonkey.ca.config;


import cn.hutool.core.collection.CollUtil;
import com.wang.jmonkey.ca.filter.AbstractAuthenticationFilter;
import com.wang.jmonkey.ca.handler.login.failure.DefaultAuthenticationFailureHandler;
import com.wang.jmonkey.ca.handler.login.success.DefaultAuthenticationSuccessHandler;
import com.wang.jmonkey.ca.handler.logout.DefaultLogoutHandler;
import com.wang.jmonkey.ca.property.SecurityProperty;
import com.wang.jmonkey.common.constant.SecurityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.ConfigurableWebServerApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;
import java.util.Map;

/**
 * @Description 授权服务配置
 * @Author HeJiawang
 * @Date 2021/5/11 17:53
 */

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private SecurityProperty securityProperty;

    @Autowired
    private DefaultAuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private DefaultAuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private DefaultLogoutHandler logoutHandler;

    @Autowired
    private ConfigurableWebServerApplicationContext context;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();

        Map<String, AbstractAuthenticationFilter> filterMap = context.getBeansOfType(AbstractAuthenticationFilter.class);
        if (CollUtil.isNotEmpty(filterMap)) {
            filterMap.entrySet().forEach(entry -> {

                entry.getValue().setAuthenticationFailureHandler(authenticationFailureHandler);
                entry.getValue().setAuthenticationSuccessHandler(authenticationSuccessHandler);
                http.addFilterBefore(entry.getValue() , UsernamePasswordAuthenticationFilter.class);
            });
        }

        http.logout().logoutUrl(SecurityConstant.Logout.path.getKey()).logoutSuccessHandler(logoutHandler);

        List<String> ignoredUrlList = securityProperty.getIgnoredUrls();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
        registry.antMatchers(ignoredUrlList.toArray(new String[ignoredUrlList.size()])).permitAll();
    }
}
